package com.atguigu.tingshu.order.receiver;

import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.order.service.MqOpsService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
@Slf4j
public class OrderInfoReceiver {


    @Autowired
    private MqOpsService mqOpsService;


    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value= MqConst.QUEUE_ORDER_LOCAL_MSG, durable = "true"),
            exchange = @Exchange(value =MqConst.EXCHANGE_LOCAL_MSG,durable = "true"),
            key = {MqConst.ROUTING_ORDER_LOCAL_MSG}
    ))
    public void updateLocalMsg(String orderNo, Message message, Channel channel){
        log.info("下游订单微服务接收到上游用户微服务的用户消息{},并且准备修改本地消息表的数据",orderNo);
        //1.判断下游消费者是否获取到了消息
        if (StringUtils.isEmpty(orderNo)){
            return; //不用消费了
        }

        //3.消费消息
        int count=mqOpsService.updateLocalMsg(orderNo);
        log.info("修改本地消息表的数据:{},",count>0?"成功":"失败");


        //4.手动应答
        //4.1获取消息的唯一标识
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        channel.basicAck(deliveryTag,false); //一条一条手动确认,不是批量确认
    }
}
